import React, { Component } from 'react'
import 'antd/dist/antd.css'
import { DatePicker, Space, Radio } from 'antd'
import { getUserInfo } from '../../../redux/actions/user'
import { connect } from 'react-redux'
import './index.css'
import { reqRegister, reqLogin, reqPatientInfo, reqLogout } from '../../../api'
import { openNotification } from '../../../util/util'

class login extends Component {
  state = {
    // register: true // true-注册，false-登录
    register: false, // true-注册，false-登录
    sex: '保密',
    dateString: '',
  }
  changeTab = () => {
    const { register } = this.state
    this.setState({
      register: !register
    })
  }
  onChangeDate = (date, dateString) => {
    this.setState({dateString})
  }
  onChangeSex = (e) => {
    const sex = e.target.value
    this.setState({sex})
  }
  login = async (data) => {
    await reqLogout()
    const res = await reqLogin(data)
    // 先判断登陆是否失败
    if (res.code === 0) {
      openNotification({ description: `账号密码错误，登录失败`, type: 'error' })
      return
    }
    // 再判断浏览器是否开启了 cookie 功能
    if ((await reqPatientInfo()).code === 0) {
      openNotification({ description: `获取用户信息失败，请开启浏览器的 cookie 功能`, type: 'error' })
      await reqLogout()
      return
    }
    if (res.code === 1) {
      // 前端存储用户信息（react-redux）
      this.props.getUserInfo(res.data)
      openNotification({ description: `登录成功`, type: 'success' })
      setTimeout(() => {
        this.props.history.replace('/profile')
      }, 2000)
    }
  }
  submit = async (e) => {
    e.preventDefault()
    if (this.state.register) {
      const res = await reqRegister({
        name: this.nameReg.value,
        pass: this.passReg.value,
        sex: this.state.sex,
        date: this.state.dateString,
      })
      openNotification({ message: '牢记', description: `注册成功，用于登录的 ID 号为${res.uid}`, type: 'success', duration: 4})
      this.login({
        uid: res.uid,
        pass: this.passReg.value,
      })
    } else {
      this.login({
        uid: this.nameLog.value,
        pass: this.passLog.value,
      })
    }
    return false
  }
  render() {
    const { register } = this.state
    return (
      <div className="wrap">
        {/* <Cover></Cover> */}
        <div className="container">
          <h2 className={`form-signin-heading ${!register ? 'active' : ''}`} onClick={this.changeTab}>登录</h2>
          <h2 className={`form-signin-heading ${register ? 'active' : ''}`} onClick={this.changeTab}>注册</h2>

          <form className="form-signin" action="#" hidden={register} onSubmit={this.submit}>
            <input ref={c=>this.nameLog=c} type="text" id="login1" className="form-control input" placeholder="ID 号" required autoFocus />
            <input ref={c=>this.passLog=c} type="password" id="login2" className="form-control input" placeholder="密码" required />
            <button className="btn btn-lg btn-primary btn-block" type="submit">登录</button>
          </form>

          <form className="form-signin" action="#" hidden={!register} onSubmit={this.submit}>
            <input ref={c=>this.nameReg=c} type="text" id="register1" className="form-control input" placeholder="姓名" required autoFocus />
            <input ref={c=>this.passReg=c} type="password" id="register2" className="form-control input" placeholder="密码" required />
            
            <div className="sex">性别：</div>
            <Radio.Group size="large" onChange={this.onChangeSex} style={{ marginTop: 16 }}>
              <Radio.Button value={'男'}>男</Radio.Button>
              <Radio.Button value={'女'}>女</Radio.Button>
              {/* <Radio.Button value={0}>男</Radio.Button>
              <Radio.Button value={1}>女</Radio.Button>
              <Radio.Button value={2}>保密</Radio.Button> */}
            </Radio.Group>
            
            <div className="item">出生日期：</div>
            <Space direction="vertical" style={{ width: "100%", height: "45px" }}>
              <DatePicker onChange={this.onChangeDate} placeholder="请选择日期" 
                style={{ width: "100%", height: "45px" }}
              />
            </Space>
            <button className="btn btn-lg btn-primary btn-block" type="submit">注册</button>
          </form>
        </div>

      </div>
    )
  }
}

export default connect(
  state => ({
    user: state.user
  }),
  {
    getUserInfo,
  }
)(login)